import getToken from '@/services/auth';
import { intl } from '@/utils';
import { notification } from 'antd';
import type { RequestInterceptor, RequestOptionsInit, ResponseError } from 'umi-request';

/**
 * 把 请求相关 都放这里，让app.tsx更清爽
 * 异常处理程序

 * @see https://beta-pro.ant.design/docs/request-cn
 */

// 拦截 每次请求，获取 token 可能需要判断一个不需要 token的请求 在要在这处理
/**
 * 请求前拦截
 * @param url
 * @param options
 * @returns
 * 如果 请求中包含  auth/ 不需要携带 token  如登录，注册等,目前所有请求都加上token
 */
export const reqInterceptor: RequestInterceptor = (url, options) => {
  const token: string = getToken();
  if (token) {
    const headers = {
      cpasToken: token,
    };
    return {
      url,
      options: {
        ...options,
        headers,
      },
    };
  }
  return {
    url,
    options,
  };
};

export const resInterceptor = (res: Response, opt: RequestOptionsInit) => {
  return {
    res,
    opt,
  };
};

/**
 * 异常处理程序
 */
export const errorHandler = (error: ResponseError): any => {
  const { response } = error;
  let errorMessage;
  let errorDescription;
  if (response && response.status) {
    const { status, statusText, url } = response;
    const msg = url;
    const sear = '/user/logout';
    const searInfo = 'user/getUserInfo';
    const isNameInfo = msg.includes(searInfo);
    const isName = msg.includes(sear);
    // 云转平台
    const sear1 = '/statistic/getCloudCovertDashboardHeaderData';
    const sear2 = 'cc/projectMng/getProjectTreeData';
    const isName1 = msg.includes(sear1);
    const isName2 = msg.includes(sear2);
    if (
      isName ||
      (isName1 && status === 401) ||
      (isName2 && status === 401) ||
      (isNameInfo && status === 401)
    )
      return;
    if (status === 401) {
      // errorMessage = intl('app.request.error.auth', '认证信息错误');
      errorMessage = intl('app.request.error.authDes', 'Token过期或未登录，请重新登录。');
      notification.error({
        message: errorMessage,
      });
    } else {
      const requestErrorMessage = intl('app.request.error', '网络异常');
      errorMessage = `${requestErrorMessage} ${status}: ${url}`;
      errorDescription = statusText;
      // errorDescription = messages[`app.request.${status}`] || statusText;
      notification.error({
        message: errorMessage,
        description: errorDescription,
      });
    }
  }
  if (!response) {
    errorMessage = intl('app.request.error', '网络异常');
    errorMessage = intl('app.request.error.des', '您的网络发生异常，无法连接服务器。');
    notification.error({
      message: errorMessage,
      description: errorDescription,
    });
  }

  throw error;
};
